﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using WinFormMapDemo.Model;

namespace WinFormMapDemo
{

    public partial class AddDeviceForm : Form
    {
        /// <summary>
        /// 经纬度
        /// </summary>
        private static   LngLat _deviceLngLat;

        private static AddDeviceForm _instance = new AddDeviceForm();

        /// <summary>
        /// 设备添加完成回调
        /// </summary>

        private static Func<DeviceInfo, int> _deviceAddCallback = null;

        private static object lockFlag = new object();
        public static AddDeviceForm Create(LngLat lngLat, string address = "",string deviceName="",Func<DeviceInfo,int> deviceAddCallBack = null)
        {

            lock (lockFlag)
            {
                if (_instance == null || _instance.IsDisposed)
                {
                    lock (lockFlag)
                    {
                        _instance = new AddDeviceForm();
                    }
                }
            }
            _deviceLngLat = lngLat;
            Random random = new Random(DateTime.Now.Millisecond);
            _instance.lblDeviceNo.Text = DateTime.Now.ToString("yyyyMMddHHmmssfff") + random.Next(0, 999).ToString("000"); ;
            _instance.txtDeviceAddress.Text = address;
            _instance.txtDeviceName.Text = deviceName;
            _deviceAddCallback = deviceAddCallBack;
            return _instance;
            
        }
        /// <summary>
        /// 更新地址
        /// </summary>
        /// <param name="address"></param>
        public static void UpdateAddress(string address)
        {
            _instance.txtDeviceAddress.Text = address;
        }

        private AddDeviceForm()
        {
            InitializeComponent();
        }

        private void btnOk_Click(object sender, EventArgs e)
        {
            

            var newDeviceInfo = new DeviceInfo()
            {
                DeviceName = this.txtDeviceName.Text,
                DeviceNo = _instance.lblDeviceNo.Text,
                DeviceAddress = this.txtDeviceAddress.Text,
                DevicePosition = _deviceLngLat,
            };

            _deviceAddCallback?.Invoke(newDeviceInfo);
            this.Hide();
        }

        private void btnCancle_Click(object sender, EventArgs e)
        {
            this.Hide();
        }
    }
}
